export class fileInfo {
    name: string;
    size: number;
}


export class TTPathTool {
    static GetFileName(filename: string) {
        if (filename.includes("/")) {
            let fi = filename.lastIndexOf("/");
            let shortname = filename.substring(fi + 1);

            return shortname

        }
        if (filename.includes("\\")) {
            let fi = filename.lastIndexOf("\\");
            let shortname = filename.substring(fi + 1);

            return shortname
        }
        return filename;
    }
    static GetPathName(filename: string): string {
        if (filename.includes("/")) {
            let fi = filename.lastIndexOf("/");
            if (fi < 0)
                return filename;

            let shortname = filename.substring(0, fi);

            return shortname

        }
        if (filename.includes("\\")) {
            let fi = filename.lastIndexOf("\\");



            let shortname = filename.substring(0, fi);

            return shortname
        }
        return "";
    }
    static GetFileNameWithoutExt(filename: string) {
        let shortname = this.GetFileName(filename);
        let di = shortname.indexOf(".");
        if (di < 0)
            return shortname;
        return shortname.substring(0, di);
    }
    static GetExt(filename: string): string {
        let shortname = this.GetFileName(filename);
        console.log("_getext:" + shortname);
        let di = shortname.indexOf(".");
        if (di < 0)
            return "";
        return shortname.substring(di);
    }
}
export class IO {

    static api: VsCodeApi  //VsCode 本身扩展的，用来向vscode 发消息，我们利用它做进一步扩展
    private static baseurl: string //我们加的，用来得到 读取资源的url，就是这个main.js所在的路径，但是vscode是隔离的，要用这个url
    private static editfile: string //得到编辑的文件名

    private static dataqueue: any[] = [];

    static GetPluginUrl(suburl: string): string {


        let subl = suburl;
        if (suburl[0] == "/")
            subl = suburl.substring(1);
        else
            subl = suburl;
        return this.baseurl + subl;
    }
    static Init(): void {

        window.onmessage = (msg) => {
            if (msg.data["cmd"] != undefined) {
                //console.log("recv:" + JSON.stringify(msg));//.data["cmd"];
                this.dataqueue.push(msg.data);
            }
        }

        this.api = acquireVsCodeApi();
        this.baseurl = getVsCodePluginPath();
        if (this.baseurl.endsWith("/") == false) {
            this.baseurl += "/";
        }
        this.editfile = getVsCodeEditFileName();//得到编辑的文件名
    }
    static GetEditFileName(): string {
        return this.editfile;
    }
    static GetEditBaseName(): string {
        return TTPathTool.GetFileNameWithoutExt(this.editfile);
    }
    static Hex2Str(data: Uint8Array | Uint8ClampedArray): string {
        let str = "";
        for (var i = 0; i < data.length; i++) {
            let h = data[i].toString(16);
            if (h.length == 1) {
                str += ("0" + h);
            }
            else {
                str += h
            }
        }
        return str;
    }
    static Str2Hex(text: string): Uint8Array {
        let u8 = new Uint8Array(text.length / 2);
        for (var i = 0; i < u8.length; i++) {
            let h = text.substring(i * 2, i * 2 + 2);
            u8[i] = parseInt(h, 16);
        }
        return u8;
    }
    static getBaseUrl(): string {
        return this.baseurl;
    }
    static getEditFile(): string {
        return this.editfile;
    }
    static async sleep(ms: number): Promise<void> {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    static async LoadEditFile_AsText(): Promise<string> {
        return await this.LoadTextFile(this.editfile)

    }

    static async FindFile(path: string, depth: number = 1): Promise<fileInfo[]> {
        let sname = path;
        while (sname.includes("\\")) {
            sname = sname.replace("\\", "/");
        }
        this.api.postMessage({ "cmd": "fs_find", "data": { "depth": depth, "path": path } });
        while (true) {
            await this.sleep(1);
            for (var i = 0; i < this.dataqueue.length; i++) {

                let q = this.dataqueue[i];
                if (q["cmd"] == "filelist") {
                    let fname = q["path"] as string;
                    while (fname.includes("\\")) {
                        fname = fname.replace("\\", "/");
                    }
                    if (fname == sname) {
                        let text = q["data"] as fileInfo[];
                        this.dataqueue.splice(i, 1);
                        return text;
                    }
                }
                if (q["cmd"] == "onerror" && q["srccmd"] == "filelist") {
                    console.error(JSON.stringify(q));
                    throw new Error(JSON.stringify(q));
                }
            }
        }
    }
    static async LoadTextFile(name: string): Promise<string> {
        let sname = name;
        while (sname.includes("\\")) {
            sname = sname.replace("\\", "/");
        }
        this.api.postMessage({ "cmd": "fs_load_text", "data": name });

        while (true) {
            await this.sleep(1);
            for (var i = 0; i < this.dataqueue.length; i++) {

                let q = this.dataqueue[i];
                if (q["cmd"] == "filedata") {
                    let fname = q["filename"] as string;
                    while (fname.includes("\\")) {
                        fname = fname.replace("\\", "/");
                    }
                    if (fname == sname) {
                        let text = q["data"] as string;
                        this.dataqueue.splice(i, 1);
                        return text;
                    }
                }
                if (q["cmd"] == "onerror" && q["srccmd"] == "fs_load_text") {
                    console.error(JSON.stringify(q));
                    throw new Error(JSON.stringify(q));
                }
            }
        }
    }
    static async LoadBinaryFile(name: string): Promise<Uint8Array> {
        let sname = name;
        while (sname.includes("\\")) {
            sname = sname.replace("\\", "/");
        }
        this.api.postMessage({ "cmd": "fs_load_binary", "data": name });

        while (true) {
            await this.sleep(1);
            for (var i = 0; i < this.dataqueue.length; i++) {

                let q = this.dataqueue[i];
                if (q["cmd"] == "filedata") {
                    let fname = q["filename"] as string;
                    while (fname.includes("\\")) {
                        fname = fname.replace("\\", "/");
                    }
                    if (fname == sname) {
                        this.dataqueue.splice(i, 1);
                        let hex = q["data"] as string;

                        return this.Str2Hex(hex);
                    }
                }
                if (q["cmd"] == "onerror" && q["srccmd"] == "fs_load_binary") {
                    console.error(JSON.stringify(q));
                    throw new Error(JSON.stringify(q));
                }
            }
        }
    }
    static async SaveBinaryFile(name: string, data: Uint8Array) {
        this.api.postMessage({ "cmd": "fs_save_binary", "data": { "data": this.Hex2Str(data), "filename": name } });
    }
    static async SaveTextFile(name: string, data: string) {
        this.api.postMessage({ "cmd": "fs_save_text", "data": { "data": data, "filename": name } });
    }

}
